package com.example.service;

import com.example.index.User;
import com.example.repository.UserRepository;
import org.elasticsearch.core.Map;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.util.Streamable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * com.example.service.UserService
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/11/1 10:57
 */
@Service
public class UserService {
    @Resource
    UserRepository repository;

    @Resource
    ElasticsearchRestTemplate template;


    // 增/改
    public User save(User user) {
        return repository.save(user);
    }

    //删除
    public void deleteById(Integer id) {
        repository.deleteById(id);
    }

    //查询
    public Optional<User> getById(Integer id) {
        return repository.findById(id);
    }

    // 自定义查询方法
    public List<User> findUsersByNameAndAddress(String name, String address) {
        List<User> users = repository.findUsersByNameAndAddress(name, address);
        return users;
    }

    /**
     * 操作索引
     */
    public void indexOperationDemo() {
        // 获取IndexOperations对象
        IndexOperations indexOperations = template.indexOps(User.class);
        // 查
        boolean exists = indexOperations.exists();
        // 删
        boolean delete = indexOperations.delete();
        // 增
        boolean flag = indexOperations.create();
        // 设置Mapping
        boolean mapping = indexOperations.putMapping();
    }


    public User saveByTemplate(User user) {
        return template.save(user);
    }

    /**
     * 操作文档
     */
    public void documentCrudDemo() {
        // 增/改
        User user = new User();
        user.setId(1);
        template.save(user);

        // 批量 增/改
        List<User> userList = new ArrayList<>();

        for (int i = 1; i <= 5; i++) {
            User tempUser = new User();
            tempUser.setId(i);
            tempUser.setName("name" + i);
            tempUser.setAddress("city" + i);
            tempUser.setAge(20 + i);
            userList.add(tempUser);
        }

        Iterable<User> users = template.save(userList);

        // 查
        User userInfo = template.get("1", User.class);

        // 删
        String delete = template.delete("1", User.class);


    }

    // 添加单个文档
    public User saveUser(User user) {
        return template.save(user);
    }

    // 批量添加文档
    public void saveBatchUsers(List<User> users) {
        template.save(users);
    }

    // 根据ID查询
    public User getUserById(String id) {
        return template.get(id, User.class);
    }

    // 条件查询
    public List<User> searchUsers(String keyword) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.matchQuery("name", keyword));
        boolQuery.should(QueryBuilders.matchQuery("address", keyword));

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withPageable(PageRequest.of(0, 10))
                .build();

        return template.search(searchQuery, User.class)
                .stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
    }

    // 分页查询
    public Page<User> searchUsersWithPage(String keyword, int page, int size) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "name", "address"))
                .withPageable(PageRequest.of(page, size))
                .build();

        Streamable<User> users = template.search(searchQuery, User.class)
                .map(SearchHit::getContent);

        return null;
    }

    // 更新文档
    public User updateUser(User user) {
        return template.save(user);
    }

    // 部分字段更新
    public void updateUserField(String id, String fieldName, Object value) {
        UpdateQuery updateQuery = UpdateQuery.builder(id)
                //.withDoc(Map.of(fieldName, value))
                .withDocument(Document.from(Map.of(fieldName, value)))
                .build();

        template.update(updateQuery, IndexCoordinates.of("user"));
    }

    // 根据ID删除
    public void deleteUserById(String id) {
        template.delete(id, User.class);
    }

    // 批量删除
    public void deleteUsers(List<String> ids) {
        ids.forEach(id -> template.delete(id, User.class));
    }

    // 根据条件删除
    public void deleteByCondition(String keyword) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name", keyword))
                .build();

        template.delete(searchQuery, User.class, IndexCoordinates.of("user"));
    }

}
